package com.qq.BFMRSE.controllerHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.qq.BFMRSE.model.BloomFilter;
import com.qq.BFMRSE.model.encryptedIndex;
import com.qq.BFMRSE.model.fileScorePair;
import com.qq.BFMRSE.model.trapDoor;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class searchHelper {
	public static double getScore(encryptedIndex enIndex,trapDoor trap)
{
	double[] MD1=enIndex.getMD1();
	double[] MD2=enIndex.getMD2();
	double[] MQ1=trap.getMD1();
	double[] MQ2=trap.getMD2();
	double score=0;
	for(int i=0;i<MD1.length;i++)
	{
		double tempScore=MD1[i]*MQ1[i]+MD2[i]*MQ2[i];
		score+=tempScore;
	}
	return score;

}
public static Map<String, encryptedIndex>getRelateFileIndex(Map<String, encryptedIndex>indexMap,List<String>fileList)
{
	Map<String, encryptedIndex>resultMap=new HashMap<String, encryptedIndex>();
	Set<String>keySet=indexMap.keySet();
	Iterator<String>iterator=fileList.iterator();
	while(iterator.hasNext())
	{
		String fileName=iterator.next();
		if(keySet.contains(fileList))
		{
			resultMap.put(fileName, indexMap.get(fileName));
		}
	}
	return resultMap;
}
public static List<String> getMostRelateFile(List<fileScorePair>fileScorePairs,int k)
{
	List<String>fileList=new ArrayList<String>();
	for(int i=1;i<fileScorePairs.size();i++)
	{
		fileScorePair key=fileScorePairs.get(i);
		int j=i-1;
		while(j>=0&&fileScorePairs.get(j).getScore()<key.getScore())
		{
			fileScorePairs.set(j+1, fileScorePairs.get(j));
			j=j-1;
		}
		fileScorePairs.set(j+1, key);
	}
	if(fileScorePairs.size()<=k)
	{
		for(int i=0;i<fileScorePairs.size();i++)
		{
			fileList.add(fileScorePairs.get(i).getFileName());
		}
	}
	else {
		for(int i=0;i<k;i++)
		{
			fileList.add(fileScorePairs.get(i).getFileName());
		}
	}
	return fileList;
}
public static trapDoor paraseJson2Trap(String searchTrap,String trapBitInfo)
{
	JSONObject jo1=JSONObject.fromObject(searchTrap);
    trapDoor reDoor=(trapDoor)jo1.toBean(jo1, trapDoor.class);
    JSONArray jaArray=JSONArray.fromObject(trapBitInfo);
    List<Integer> list=jaArray.toList(jaArray);
    BloomFilter bFilter=new BloomFilter();
    Iterator<Integer>iterator=list.iterator();
    while(iterator.hasNext())
    {
    	bFilter.getBits().set(iterator.next());
    }
    reDoor.setBf(bFilter);
    return reDoor;
}


}
